﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Pulse
{
    class Explosion
    {
        public Sprite explosionSprite;
        Vector2 position;
        Vector2 direction;
        float speed;
        float drawOrder = 0.0f;

        bool active = false;
        public bool trigger = false;

        public Explosion(Texture2D texture, int X, int Y, int W, int H, int Frames)
        {
            explosionSprite = new Sprite(texture);
            explosionSprite.AddAnimation("explode", X, Y, W, H, Frames, texture.Width, 0.01f);
            explosionSprite.AddAnimation("none", 0, 0, 1, 1, 1, 1, 1.0f);

            explosionSprite.animating = false;
            explosionSprite.CurrentAnimation = "explode";
        }

        public bool IsActive
        {
            get { return active; }
        }

        public Vector2 Position
        {
            get { return position; }
            set { position = value; }
        }

        public void Activate(Vector2 newPosition, Vector2 unitDirection, float newSpeed)
        {
            position = newPosition;
            direction = unitDirection;
            speed = newSpeed;
            explosionSprite.animating = true;
            active = true;
            trigger = true;
        }

        public void Update(GameTime gametime, float draw)
        {
            drawOrder = draw;

            if (active)
            {
                Position += direction * speed;
                explosionSprite.Update(gametime);
                if (explosionSprite.CurrentFrameAnimation.currentFrame >= explosionSprite.CurrentFrameAnimation.frameCount - 1)
                {
                    active = false;
                }

                if (trigger)
                    trigger = false;
            }
        }

        public void Draw(SpriteBatch spritebatch)
        {
            if (active)
            {
                //explosionSprite.Draw(spritebatch);
                spritebatch.Draw(explosionSprite.spriteTexture, Position,
                    explosionSprite.CurrentFrameAnimation.getCurrentSourceRectangle, Color.White,
                    0.0f, Vector2.Zero, 1.0f, SpriteEffects.None, drawOrder); 
            }
        }
    }
}
